package com.cloudpivot.receivales.equipmentinstallation.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.equipmentinstallation.domain.InstallationReportEntity;
import com.cloudpivot.receivales.equipmentinstallation.domain.ReportRspDTO;
import com.cloudpivot.receivales.equipmentinstallation.service.EquipmentInstallationReportService;
import com.cloudpivot.receivales.workorder.domain.WorkorderReportRspDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Map;

@Controller
@Slf4j
@RequestMapping("/equipmentInstallationReport")
public class RquipmentInstallationReportController {
    @Autowired
    private EquipmentInstallationReportService equipmentInstallationReportService;

    /**
     * 创建设备安装单
     */
    @PostMapping("/createReportOfRequest")
    @ResponseBody
    public ReportRspDTO createReportOfRequest(@RequestBody JSONObject entity){
    //public void createReportOfRequest(HttpServletResponse response){
        try{
            InstallationReportEntity installationReportEntity = JSON.parseObject(entity.toJSONString(), InstallationReportEntity.class);
            Map<String,Object> rspMap = equipmentInstallationReportService.createStreambase64(installationReportEntity);
//            response.reset();
//            response.setCharacterEncoding("UTF-8");
//            response.addHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(rspMap.get("fileName").toString()));
//            response.setContentType("application/octet-stream");
//            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
//            outputStream.write((byte[]) rspMap.get("bytes"));
//            outputStream.flush();
            Base64.Encoder encoder = Base64.getEncoder();
            String base64 = encoder.encodeToString((byte[]) rspMap.get("bytes"));
            log.info("返回 base64 长度{}", base64.length());
            return new ReportRspDTO(1, base64);
            //return base64;
        }catch(Exception e){
            e.printStackTrace();
            return new ReportRspDTO(-99,null);
            //return "null";
        }

    }
}
